package net.xdclass.Config;

import com.mysql.cj.jdbc.interceptors.ConnectionLifecycleInterceptor;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;



@Configuration
public class RestTemplateConfig {

	@Bean
	public RestTemplate getRestTemplate(ClientHttpRequestFactory clientHttpRequestFactory){
     return new RestTemplate(clientHttpRequestFactory);
	}


    @Bean
	public ClientHttpRequestFactory getClientHttpRequestFactory(){
//		HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient());
//		return factory;
		return new HttpComponentsClientHttpRequestFactory(httpClient());

	}
//
//	@Bean
//	public ClientHttpRequestFactory getClientHttpRequestFactory(){
//		SimpleClientHttpRequestFactory factory = new 	SimpleClientHttpRequestFactory();
//		factory.setReadTimeout(10000);
//		factory.setConnectTimeout(10000);
//		return factory;
//	}


    @Bean
	public HttpClient httpClient() {
		Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
				.register("http", PlainConnectionSocketFactory.getSocketFactory())
				.register("https", SSLConnectionSocketFactory.getSocketFactory())
				.build();
		PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
		// 连接池最大连接数是500个
		connectionManager.setMaxTotal(2000);
		//maxperroute 是对maxtotal的细分，每个主机并发最大是300
		connectionManager.setDefaultMaxPerRoute(2000);
		RequestConfig requestConfig = RequestConfig.custom()
				// 返回数据的超时时间
				.setSocketTimeout(20000)
				.setConnectTimeout(10000)
				.setConnectionRequestTimeout(1000)
				.build();
		CloseableHttpClient closeableHttpClient = HttpClientBuilder.create()
				.setDefaultRequestConfig(requestConfig)
				.setConnectionManager(connectionManager)
				.build();
		return closeableHttpClient;
	}
}
